package com.seezoon.application.user.executor;

import com.seezoon.application.user.dto.ResetPasswordCmd;
import com.seezoon.domain.service.user.UserInfoService;
import com.seezoon.domain.service.user.vo.UserRegisterTypeVO;
import com.seezoon.infrastructure.dto.Response;
import com.seezoon.infrastructure.error.ErrorCode;
import com.seezoon.infrastructure.properties.AppProperties;
import com.seezoon.infrastructure.security.TotpService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.nio.charset.StandardCharsets;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

/**
 * 重置密码
 */
@RequiredArgsConstructor
@Slf4j
@Component
@Validated
public class ResetPasswordCmdExe {

    private final AppProperties appProperties;
    private final TotpService totpService;
    private final UserInfoService userInfoService;

    public Response execute(@Valid @NotNull ResetPasswordCmd cmd) {
        UserRegisterTypeVO.check(cmd.getResetType());

        // 检查验证码
        boolean verify = totpService.validateCode(
                (appProperties.getSecretKey() + cmd.getUsername()).getBytes(StandardCharsets.UTF_8),
                cmd.getCode());
        if (!verify && appProperties.getCodeValidateEnabled()) {
            return Response.error(ErrorCode.CODE_NOT_MATCH);
        }

        // 重置密码
        Long uid = userInfoService.resetPassword(cmd.getUsername(), cmd.getNewPassword());
        log.info("reset password completed for uid: {}", uid);
        return Response.success();
    }
} 